<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>注册页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-image: url('${pageContext.request.contextPath}/images/register.png');
            background-size: cover;
            background-position: center;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .register-container {
            background-color: rgba(255, 255, 255, 0.9);
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            width: 400px;
        }
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 1.5rem;
        }
        .form-group {
            margin-bottom: 1rem;
        }
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
        }
        .form-control {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn-register {
            width: 100%;
            padding: 0.75rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 1rem;
        }
        .btn-register:hover {
            background-color: #0056b3;
        }
        .login-link {
            display: block;
            text-align: center;
            margin-top: 1rem;
            color: #007bff;
            text-decoration: none;
        }
        .login-link:hover {
            text-decoration: underline;
        }
        .error {
            color: #dc3545;
            font-size: 0.875rem;
            display: none;
        }
    </style>
</head>

<link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css">
    <script src="${pageContext.request.contextPath}/bootstrap/js/jquery-2.1.0.min.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>

<body>

<div class="register-container">
    <h2>注册</h2>
    <form action="${pageContext.request.contextPath}/user/zhuce" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="avatar">头像</label>
            <input type="file" class="form-control" id="avatar" name="image">
            <span class="error" id="avatarError"></span>
            <div id="imagePreview" style="margin-top: 10px; display: none;">
                <img id="preview" src="#" alt="图片预览" style="max-width: 100px; max-height: 100px; border-radius: 50%;"/>
            </div>
        </div>
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" class="form-control" id="username" name="u_name">
            <span class="error" id="usernameError"></span>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" class="form-control" id="password" name="u_pass">
            <span class="error" id="passwordError"></span>
        </div>
        <div class="form-group">
            <label for="confirmPassword">确认密码</label>
            <input type="password" class="form-control" id="confirmPassword" name="u_confirmPass">
            <span class="error" id="confirmPasswordError"></span>
        </div>
        <div class="form-group">
            <label for="u_sex">性别</label>
            <select class="form-control" id="u_sex" name="u_sex">
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
        </div>
        <div class="form-group">
            <label for="email">邮箱</label>
            <input type="email" class="form-control" id="email" name="u_email">
            <span class="error" id="emailError"></span>
        </div>
        <div class="form-group">
            <label for="phone">手机号</label>
            <input type="tel" class="form-control" id="phone" name="u_phone">
            <span class="error" id="phoneError"></span>
        </div>
        <div class="form-group">
            <label for="birthday">生日</label>
            <input type="date" class="form-control" id="birthday" name="u_birthday">
            <span class="error" id="birthdayError"></span>
        </div>

        <button type="submit" class="btn-register">注册</button>
    </form>
    <a href="${pageContext.request.contextPath}/luyou/login" class="login-link">已有账号？立即登录</a>
</div>

<!-- 引入外部 JavaScript 文件 -->
<!-- <script src="js/register.js"></script> -->
<script>

// 页面加载完成后绑定事件
$(document).ready(function() {
    // 绑定用户名输入框的blur事件
    document.getElementById('username').addEventListener('blur', checkUsername);
});

// 检查用户名是否重复
function checkUsername() {
    const username = document.getElementById('username').value.trim();
    const userId = 0; // 将 userId 设置为默认值 0
    console.log('checkUsername called with username:', username); // 调试信息
    if (username.length < 3 || username.length > 20) return;

    $.ajax({
        url: '${pageContext.request.contextPath}/user/checkUsername',
        type: 'POST',
        data: { username: username, userId: userId || 0 }, // 确保 userId 不为 null
        success: function(data) {
            console.log('AJAX response:', data); // 调试信息
            if (data.exists) {
                document.getElementById('usernameError').textContent = '用户名已存在，请重新输入';
                document.getElementById('usernameError').style.display = 'block';
                console.log('Setting focus to username input'); // 调试信息
                document.getElementById('username').focus();
            } else {
                document.getElementById('usernameError').style.display = 'none';
            }
        },
        error: function(error) {
            console.error('Error:', error);
        }
    });
}

// 表单提交验证
document.querySelector('form').addEventListener('submit', function(e) {
    let isValid = true;

    // 验证用户名
    const username = document.getElementById('username').value.trim();
    if (username.length < 3 || username.length > 20) {
        document.getElementById('usernameError').textContent = '用户名长度应在3到20个字符之间';
        document.getElementById('usernameError').style.display = 'block';
        isValid = false;
    }

    // 检查用户名是否重复（同步验证）
    if (isValid) {
        const userId = "0"; // 获取当前用户的 ID
        $.ajax({
            url: '${pageContext.request.contextPath}/user/checkUsername',
            type: 'POST',
            data: { username: username, userId: userId }, // 传递用户名和用户 ID
            async: false, // 同步请求
            success: function(data) {
                if (data.exists) {
                    document.getElementById('usernameError').textContent = '用户名已存在，请重新输入';
                    document.getElementById('usernameError').style.display = 'block';
                    isValid = false;
                }
            },
            error: function(error) {
                console.error('Error:', error);
                isValid = false;
            }
        });
    }

    // 其他验证逻辑保持不变
    // 验证密码
    const password = document.getElementById('password').value;
    if (password.length < 6) {
        document.getElementById('passwordError').textContent = '密码长度至少为6个字符';
        document.getElementById('passwordError').style.display = 'block';
        isValid = false;
    }

    // 验证确认密码
    const confirmPassword = document.getElementById('confirmPassword').value;
    if (password !== confirmPassword) {
        document.getElementById('confirmPasswordError').textContent = '两次输入的密码不一致';
        document.getElementById('confirmPasswordError').style.display = 'block';
        isValid = false;
    }

    // 验证邮箱
    const email = document.getElementById('email').value;
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
        document.getElementById('emailError').textContent = '请输入有效的邮箱地址';
        document.getElementById('emailError').style.display = 'block';
        isValid = false;
    }

    if (!isValid) {
        e.preventDefault();
    }
});

document.getElementById('avatar').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
            document.getElementById('avatarError').textContent = '请选择有效的图片文件';
            document.getElementById('avatarError').style.display = 'block';
            return;
        }

        // 验证文件大小
        // if (file.size > 20 * 1024 * 1024) { // 2MB
        //     document.getElementById('avatarError').textContent = '文件大小不能超过20MB';
        //     document.getElementById('avatarError').style.display = 'block';
        //     return;
        // }

        // 显示预览
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('preview').src = e.target.result;
            document.getElementById('imagePreview').style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
});


</script>
</body>
</html>
